<template>
  <el-dialog
    title="用户注册"
    :visible.sync="dialogVisible"
    width="600px"
    :before-close="handleClose"
    center
  >
    <span
      ><el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        label-position="left"
      >
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :data="uploadObj"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="ruleForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" show-password></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="16" style="margin-right:10px;">
            <el-form-item label="图形码" prop="code">
              <el-input v-model="ruleForm.code"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <img
              :src="registerCodeUrl"
              alt=""
              style="width:100%;height:40px;"
              @click="changeRegisterCodeUrl"
            />
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16" style="margin-right:10px;">
            <el-form-item label="验证码" prop="rcode">
              <el-input v-model="ruleForm.rcode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-button style="width:175px" @click="getRcode"
              >获取用户验证码</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </span>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="register">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: 'Register',
  data () {
    return {
      uploadObj: {
        image: null
      },
      uploadUrl: process.env.VUE_APP_BASEURL + '/uploads',
      imageUrl: '', // 图片预览地址
      registerCodeUrl: process.env.VUE_APP_BASEURL + '/captcha?type=sendsms',
      dialogVisible: false,
      ruleForm: {
        avatar: '',
        username: '',
        email: '',
        phone: '',
        password: '',
        code: '',
        rcode: ''
      },
      rules: {
        avatar: [
          { required: true, message: '头像不能为空！', trigger: 'change' }
        ],
        username: [
          { required: true, message: '昵称不能为空！', trigger: 'blur' }
        ],
        email: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) return callback(new Error('邮箱不能为空！'))
              // 下面是高所eslint对下一行代码不校验
              // eslint-disable-next-line
              const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
              if (!reg.test(value))
                return callback(new Error('邮箱格式不正确！'))
              callback()
            },
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) return callback(new Error('手机号不能为空！'))
              const reg = /^1[3-9][0-9]{9}$/
              if (!reg.test(value)) return callback(new Error('手机号不合法！'))
              callback()
            },
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '密码不能为空！', trigger: 'blur' },
          {
            min: 6,
            max: 16,
            message: '密码长度在6-16位！',
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '图形码不能为空！', trigger: 'blur' }
        ],
        rcode: [
          { required: true, message: '验证码不能为空！', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    dialogVisible (newValue) {
      if (!newValue) {
        // 当关闭对话框时清空
        this.$refs.ruleForm.resetFields()
        // 将头像预览的地址改为空
        this.imageUrl = ''
      }
    }
  },
  methods: {
    handleClose () {
      this.dialogVisible = false
      // 以下是关闭对话框时，清空对话框的内容
      // this.$refs.ruleForm.resetFields()
      // this.$refs.ruleForm.clearValidate()
    },
    changeRegisterCodeUrl () {
      this.registerCodeUrl =
        process.env.VUE_APP_BASEURL +
        `/captcha?type=sendsms&t=${new Date() - 0}`
    },
    async getRcode () {
      let count = 0
      this.$refs.ruleForm.validateField(['phone', 'code'], errorMessage => {
        if (!errorMessage) count++
      })
      if (count == 2) {
        const res = await this.$axios.post('/sendsms', {
          code: this.ruleForm.code,
          phone: this.ruleForm.phone
        })
        if (res.code == 200) {
          this.ruleForm.rcode = res.data.captcha
        } else {
          this.$message.error(res.message)
          this.changeRegisterCodeUrl()
        }
      }
    },

    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      if (res.code == 200) {
        this.ruleForm.avatar = res.data.file_path
      }
    },
    beforeAvatarUpload (file) {
      const isImage =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG/png/gif 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      // 给额外参数Image赋值
      this.uploadObj.image = file
      return isImage && isLt2M
    },
    register () {
      this.$refs.ruleForm.validate(async valid => {
        // 如果有信息没有填或填错，valid为true，则直接return
        if (!valid) return
        // 信息填完，则发送请求注册
        const res = await this.$axios.post('/register', this.ruleForm)
        console.log(res)
        if (res.code === 200) {
          this.$message.success('注册成功！')
          this.dialogVisible = false
        }
      })
    }
  }
}
</script>
<style lang="less">
.avatar-uploader {
  text-align: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px !important;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  text-align: center;
}
</style>
